package com.tgy.esp32Service.exception;

import com.tgy.esp32Service.constant.CommonConsts;
import com.tgy.esp32Service.dto.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;

/***
 * @ClassName: PredictionGlobalExceptionHandler
 * @Description: 全局异常处理
 * @Auther: tanggy3
 * @Date: 15:34 2022/9/14
 * @version : V1.0
 */
@ControllerAdvice
@Slf4j
public class EspGlobalExceptionHandler {

    /**
     * 自定义全局异常
     */
    @ExceptionHandler(value = EspGlobalException.class)
    @ResponseBody
    public R<Object> handlerPredictionGlobalException(EspGlobalException e){
        log.error("PredictionGlobalException，原因是: {}", e.getMessage());
        return R.failed(e.getBasicErrorType());
    }

    /**
     * Controller上一层相关异常（部分）
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler({
            NoHandlerFoundException.class,
            HttpRequestMethodNotSupportedException.class,
            HttpMediaTypeNotSupportedException.class,
            MissingServletRequestParameterException.class
    })
    @ResponseBody
    public R<Object> handleServletException(Exception e) {
        log.error("handleServletException: " + e.getMessage(), e);
        R<Object> r = new R<>();
        r.setStatus(CommonConsts.FAIL_TIP);
        if(e instanceof NoHandlerFoundException) {
            r = R.failed(BasicErrorType.METHOD_NOT_FOUND_ERROR);
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            r = R.failed(BasicErrorType.METHOD_NOT_SUPPORT_ERROR);
        } else if (e instanceof MissingServletRequestParameterException) {
            r = R.failed(BasicErrorType.REQUEST_PARAMETER_MISS_ERROR);
        } else if (e instanceof HttpMediaTypeNotSupportedException) {
            r = R.failed(BasicErrorType.MEDIA_TYPE_NOT_SUPPORT_ERROR);
        }

        return r;
    }

    /**
     * 空指针异常
     */
    @ExceptionHandler(value =NullPointerException.class)
    @ResponseBody
    public R<Object> handlerNullPointerException(HttpServletRequest req, Exception e){
        log.error("空指针异常！原因是:", e);
        return R.failed(BasicErrorType.NULLPOINTER_SYSTEM_ERROR);
    }

    /**
     * 其他异常
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public R<Object> handlerException(HttpServletRequest req, Exception e){
        log.error("未知异常！原因是:", e);
        return R.failed(BasicErrorType.UNKNOW_ERROR);
    }
}
